import IScroll from 'iscroll/build/iscroll-probe'
// let IScroll = window.IScroll
function onTopLoaded() {
  let node = this.elm.querySelector('.iscroll-down-box')
  node.innerHTML = ''
  node.classList.add('finish')
  node.classList.remove('loading')
  setTimeout(() => {
    node.classList.add('finish-out')
    setTimeout(() => {
      node.classList.remove('finish')
      node.classList.remove('finish-out')
      node.innerHTML = node.getAttribute('data-downText')
      this.scroll.enabled = true
    }, 500)
  }, 500)
}

function onBottomLoaded(){
  let wrapper = this.elm.querySelector('div')
  let node = this.elm.querySelector('.iscroll-up-box')
  this.callPullUp = false
  if(this.bottomAllLoaded){
    node.style.display = 'none'
    this.scroll.refresh()
  }
  setTimeout(()=>{
    wrapper.appendChild(node)
  },0)
}

const VIScroll = {
  install(Vue, options) {
    Vue.directive('iscroll', {
      bind(el, binding, vnode, oldVnode) {
        let bindingV = binding.value;
        // 设置iscorll属性的参数
        let iscrollOptions = {}
        // Object.assign并不受安卓原生浏览器的支持！导致错误--造成iscroll无效
        // 解决方法是使用 babel-plugin-transform-runtime
        Object.assign(iscrollOptions, options, bindingV)
        let downText = iscrollOptions.downText ? iscrollOptions.downText : '<i class="iconfont icon-xia"></i>下拉更新'
        let upText = iscrollOptions.upText ? iscrollOptions.upText : '加载中...'
        if (iscrollOptions.pullDown || iscrollOptions.pullUp) {
          iscrollOptions.probeType = 3
        }
        // 使用vnode绑定iscroll是为了让iscroll对象能够夸状态传递，避免iscroll重复建立
        setTimeout(() => {
          // 阻止touchmove默认事件
          el.addEventListener('touchmove', (e)=>{e.preventDefault()})
          vnode.scroll = new IScroll(el, iscrollOptions);
          let wrapper = el.querySelector('div')
          if (iscrollOptions.pullDown) {
            let topDistance = iscrollOptions.topDistance ? iscrollOptions.topDistance : 70
            let nodeDown = document.createElement('span')
            vnode.callPullDown = false
            nodeDown.className = 'iscroll-down-box iconfont'
            nodeDown.setAttribute('data-downText', downText)
            nodeDown.innerHTML = downText
            wrapper.insertBefore(nodeDown, wrapper.childNodes[0])
            vnode.onTopLoaded = onTopLoaded
            vnode.scroll.on('scroll', function () {
              let y = Math.round(this.y)
              if (y > topDistance && !vnode.callPullDown) {
                nodeDown.innerHTML = "<i class=\"iconfont icon-shang\"></i>释放加载"
                vnode.callPullDown = true
              }
            })
            vnode.scroll.on('scrollEnd', function () {
              if (vnode.callPullDown) {
                this.enabled = false
                vnode.callPullDown = false
                nodeDown.classList.add('loading')
                nodeDown.innerHTML = ""
                iscrollOptions.pullDown(vnode)
              }
            })
          }
          if(iscrollOptions.pullUp){
            let bottomDistance = iscrollOptions.bottomDistance ? iscrollOptions.bottomDistance : 30
            let nodeUp = document.createElement('span')
            vnode.callPullUp = false
            vnode._bottomAllLoaded = false
            nodeUp.className = 'iscroll-up-box'
            nodeUp.setAttribute('data-upText', upText)
            nodeUp.innerHTML = upText
            wrapper.appendChild(nodeUp)
            vnode.onBottomLoaded = onBottomLoaded
            vnode.scroll.refresh();

            Object.defineProperty(vnode, "bottomAllLoaded", {
              get: function () {
                return vnode._bottomAllLoaded
              },
              set: function (value) {
                vnode._bottomAllLoaded = value
                if(value){
                  nodeUp.style.display = 'none'
                }else{
                  nodeUp.style.display = 'block'
                }
                if(value!==null){
                  vnode.scroll.refresh()
                }
              }
            });

            vnode.scroll.on('scroll', function () {
              let y = Math.round(this.y)
              let maxY = this.maxScrollY
              if (y-bottomDistance < maxY && !vnode.callPullUp && !vnode.bottomAllLoaded) {
                vnode.callPullUp = true
                iscrollOptions.pullUp(vnode)
              }
            })
          }
        }, 0)
      },
      update(el, binding, vnode, oldVnode) {
        // 将scroll绑定到新的vnode上
        // 使用settimeout让refresh跳到事件流结尾，保证refresh时数据已经更新完毕
        setTimeout(() => {
          vnode.scroll = oldVnode.scroll;
          vnode.scroll && vnode.scroll.refresh();
        }, 0)
      },
      unbind(el, binding, vnode, oldVnode) {
        /**
         * 解除绑定时要把iscroll销毁
         */
        setTimeout(()=>{
          vnode.scroll = oldVnode.scroll;
          vnode.scroll &&vnode.scroll.destroy();
          vnode.scroll = null;
          vnode.callPullDown = null
          vnode.callPullUp = null
          vnode.onTopLoaded = null
          vnode.onBottomLoaded = null
          vnode.bottomAllLoaded = null
        },0)
      }
    })
  }
}
export default VIScroll;